/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-10-30     SummerGift   change to new framework
 * 2019-01-24     Mxf          GD32E10X change to new framework
 */
 
#include "board.h"
#include "drv_usart.h"
#include "drv_config.h"

#ifdef RT_USING_SERIAL

//#define DRV_DEBUG
#define LOG_TAG             "drv.usart"
#include <drv_log.h>

#if !defined(BSP_USING_UART0) && !defined(BSP_USING_UART1) && !defined(BSP_USING_UART2) && !defined(BSP_USING_UART3) && !defined(BSP_USING_UART4)
#error "Please define at least one BSP_USING_UARTx"
/* this driver can be disabled at menuconfig → RT-Thread Components → Device Drivers */
#endif

#ifdef RT_SERIAL_USING_DMA
static void uart_dma_config(struct rt_serial_device *serial);
#endif

enum
{
#ifdef BSP_USING_UART0
    UART0_INDEX,
#endif    
#ifdef BSP_USING_UART1
    UART1_INDEX,
#endif
#ifdef BSP_USING_UART2
    UART2_INDEX,
#endif
#ifdef BSP_USING_UART3
    UART3_INDEX,
#endif
#ifdef BSP_USING_UART4
    UART4_INDEX,
#endif
};

static struct uart_config uart_config[] =
{
#ifdef BSP_USING_UART0
        UART0_CONFIG,
#endif    
#ifdef BSP_USING_UART1
        UART1_CONFIG,
#endif
#ifdef BSP_USING_UART2
        UART2_CONFIG,
#endif
#ifdef BSP_USING_UART3
        UART3_CONFIG,
#endif
#ifdef BSP_USING_UART4
        UART4_CONFIG,
#endif
};

static struct uart_driver uart_obj[sizeof(uart_config) / sizeof(uart_config[0])] = {0};

static rt_err_t uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg)
{
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);
    RT_ASSERT(cfg != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    uart_drv->init.periph              = uart_drv->config->periph;
    uart_drv->init.BaudRate            = cfg->baud_rate;
    uart_drv->init.HwFlowCtl           = UART_HWCONTROL_NONE;
    uart_drv->init.Mode                = UART_MODE_TX_RX;
    
    switch (cfg->data_bits)
    {
    case DATA_BITS_8:
        uart_drv->init.WordLength = USART_WL_8BIT;
        break;
    case DATA_BITS_9:
        uart_drv->init.WordLength = USART_WL_9BIT;
        break;
    default:
        uart_drv->init.WordLength = USART_WL_8BIT;
        break;
    }
    switch (cfg->stop_bits)
    {
    case STOP_BITS_1:
        uart_drv->init.StopBits   = USART_STB_1BIT;
        break;
    case STOP_BITS_2:
        uart_drv->init.StopBits   = USART_STB_2BIT;
        break;
    default:
        uart_drv->init.StopBits   = USART_STB_1BIT;
        break;
    }
    switch (cfg->parity)
    {
    case PARITY_NONE:
        uart_drv->init.Parity     = USART_PM_NONE;
        break;
    case PARITY_ODD:
        uart_drv->init.Parity     = USART_PM_ODD;
        break;
    case PARITY_EVEN:
        uart_drv->init.Parity     = USART_PM_EVEN;
        break;
    default:
        uart_drv->init.Parity     = USART_PM_NONE;
        break;
    }

    if(uart_init(&uart_drv->init) != RT_EOK)
    {
        return RT_ERROR;
    }
    
    return RT_EOK;
}

static rt_err_t uart_control(struct rt_serial_device *serial, int cmd, void *arg)
{
    struct uart_driver *uart_drv;
#ifdef RT_SERIAL_USING_DMA
    rt_ubase_t ctrl_arg = (rt_ubase_t)arg;
#endif
    
    RT_ASSERT(serial != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    switch (cmd)
    {
    /* disable interrupt */
    case RT_DEVICE_CTRL_CLR_INT:
        /* disable rx irq */
        NVIC_DisableIRQ(uart_drv->config->irq_type);
        /* disable interrupt */
        usart_interrupt_disable(uart_drv->config->periph, USART_INT_RBNE);
        break;
    /* enable interrupt */
    case RT_DEVICE_CTRL_SET_INT:
        /* enable rx irq */
        NVIC_EnableIRQ(uart_drv->config->irq_type);
        /* enable interrupt */
        usart_interrupt_enable(uart_drv->config->periph, USART_INT_RBNE);
        break;

#ifdef RT_SERIAL_USING_DMA
    case RT_DEVICE_CTRL_CONFIG:
        if (ctrl_arg == RT_DEVICE_FLAG_DMA_RX)
        {
            uart_dma_config(serial);
        }
        break;
#endif
    }
    return RT_EOK;
}

static int uart_putc(struct rt_serial_device *serial, char c)
{
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);

    uart_drv = (struct uart_driver *)serial->parent.user_data;
    UART_INSTANCE_CLEAR_FUNCTION(uart_drv->config->periph, USART_FLAG_TC);

    usart_data_transmit(uart_drv->config->periph,c);
    
    while (usart_flag_get(uart_drv->config->periph, USART_FLAG_TC) == RESET);
    return 1;
}

static int uart_getc(struct rt_serial_device *serial)
{
    int ch;
    struct uart_driver *uart_drv;
    RT_ASSERT(serial != RT_NULL);
    uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    ch = -1;
    if (usart_flag_get(uart_drv->config->periph, USART_FLAG_RBNE) != RESET)
    {
        ch = usart_data_receive(uart_drv->config->periph);
    }
    return ch;
}

static const struct rt_uart_ops uart_ops =
{
    .configure = uart_configure,
    .control = uart_control,
    .putc = uart_putc,
    .getc = uart_getc,
};

/**
 * Uart common interrupt process. This need add to uart ISR.
 *
 * @param serial serial device
 */
static void uart_isr(struct rt_serial_device *serial)
{
    struct uart_driver *uart_drv;
#ifdef RT_SERIAL_USING_DMA
    rt_size_t recv_total_index, recv_len;
    rt_base_t level;
#endif
    
    RT_ASSERT(serial != RT_NULL);

    uart_drv = (struct uart_driver *) serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);

    /* UART in mode Receiver -------------------------------------------------*/
    if ((usart_flag_get(uart_drv->config->periph, USART_FLAG_RBNE) != RESET) &&
        (usart_interrupt_flag_get(uart_drv->config->periph, USART_INT_FLAG_RBNE) != RESET))
    {
        rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_IND);
    }
#ifdef RT_SERIAL_USING_DMA
    else if ((uart_drv->uart_dma_flag) && (usart_flag_get(uart_drv->config->periph, USART_FLAG_IDLE) != RESET) &&
             (usart_interrupt_flag_get(uart_drv->config->periph, USART_INT_FLAG_IDLE) != RESET))
    {
        level = rt_hw_interrupt_disable();
        recv_total_index = serial->config.bufsz - DMA_CHCNT(uart_drv->dma.dma_periph,uart_drv->dma.channel);
        recv_len = recv_total_index - uart_drv->dma.last_index;
        uart_drv->dma.last_index = recv_total_index;
        rt_hw_interrupt_enable(level);

        if (recv_len)
        {
            rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_DMADONE | (recv_len << 8));
        }
        
        usart_flag_get(uart_drv->config->periph,USART_FLAG_IDLE); //clear IDLE flag
        usart_data_receive(uart_drv->config->periph);
    }
#endif
    else
    {
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_ORERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            usart_flag_get(uart_drv->config->periph,USART_FLAG_ORERR);
            usart_data_receive(uart_drv->config->periph);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_NERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            usart_flag_get(uart_drv->config->periph,USART_FLAG_NERR);
            usart_data_receive(uart_drv->config->periph);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_FERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            usart_flag_get(uart_drv->config->periph,USART_FLAG_FERR);
            usart_data_receive(uart_drv->config->periph);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_PERR) != RESET) //soft ware read USART_STAT0，then read USART_DATA clear this bit
        {
            usart_flag_get(uart_drv->config->periph,USART_FLAG_PERR);
            usart_data_receive(uart_drv->config->periph);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_LBD) != RESET) //soft chear this bit
        {
            UART_INSTANCE_CLEAR_FUNCTION(uart_drv->config->periph,USART_FLAG_LBD);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_CTS) != RESET)//soft chear this bit
        {
            UART_INSTANCE_CLEAR_FUNCTION(uart_drv->config->periph,USART_FLAG_CTS);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_TC) != RESET) //soft chear this bit
        {
            UART_INSTANCE_CLEAR_FUNCTION(uart_drv->config->periph,USART_FLAG_TC);
        }
        if (usart_flag_get(uart_drv->config->periph, USART_FLAG_RBNE) != RESET) //soft chear this bit
        {
            UART_INSTANCE_CLEAR_FUNCTION(uart_drv->config->periph,USART_FLAG_RBNE);
        }
    }
}

void dma_rx_done_isr(struct rt_serial_device *serial)
{
    struct uart_driver *uart_drv;
    rt_size_t recv_len;
    rt_base_t level;

    uart_drv = (struct uart_driver *) serial->parent.user_data;
    serial = &uart_drv->serial;

    level = rt_hw_interrupt_disable();

    recv_len = serial->config.bufsz - uart_drv->dma.last_index;
    uart_drv->dma.last_index = 0;

    rt_hw_interrupt_enable(level);
    if (recv_len)
    {
        rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_DMADONE | (recv_len << 8));
    }
    
    dma_flag_clear(uart_drv->config->dma_rx->dma_periph,uart_drv->config->dma_rx->channel,DMA_FLAG_FTF);
}

#if defined(BSP_USING_UART0)
void USART0_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART0_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART0_RX_USING_DMA)
void USART0_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART0_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_USART0_RX_USING_DMA) */
#endif /* BSP_USING_UART0*/

#if defined(BSP_USING_UART1)
void USART1_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART1_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART1_RX_USING_DMA)
void USART1_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART1_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_UART1_RX_USING_DMA) */
#endif /* BSP_USING_UART1 */

#if defined(BSP_USING_UART2)
void USART2_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART2_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART2_RX_USING_DMA)
void UART2_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART2_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(RT_SERIAL_USING_DMA) && defined(BSP_UART2_RX_USING_DMA) */
#endif /* BSP_USING_UART2 */

#if defined(BSP_USING_UART3)
void UART3_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART3_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART3_RX_USING_DMA)
void UART3_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    dma_rx_done_isr(&(uart_obj[UART3_INDEX].serial));

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(BSP_UART_USING_DMA_RX) && defined(BSP_UART3_RX_USING_DMA) */
#endif /* BSP_USING_UART3*/

#if defined(BSP_USING_UART4)
void UART4_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    uart_isr(&(uart_obj[UART4_INDEX].serial));
    
    /* leave interrupt */
    rt_interrupt_leave();
}
#if defined(RT_SERIAL_USING_DMA) && defined(BSP_UART4_RX_USING_DMA)
void UART4_DMA_RX_IRQHandler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    HAL_DMA_IRQHandler(&uart_obj[UART4_INDEX].dma.handle);

    /* leave interrupt */
    rt_interrupt_leave();
}
#endif /* defined(BSP_UART_USING_DMA_RX) && defined(BSP_UART4_RX_USING_DMA) */
#endif /* BSP_USING_UART4*/

#ifdef RT_SERIAL_USING_DMA
static void uart_dma_config(struct rt_serial_device *serial)
{
    RT_ASSERT(serial != RT_NULL);
    struct uart_driver *uart_drv = (struct uart_driver *)serial->parent.user_data;
    RT_ASSERT(uart_drv != RT_NULL);
    struct rt_serial_rx_fifo *rx_fifo;
    
    LOG_D("%s dma config start", uart_drv->config->name);

    
    rx_fifo = (struct rt_serial_rx_fifo *)serial->serial_rx;
    
    /* DMA clock config */
    rcu_periph_clock_enable(uart_drv->config->dma_rx->dma_rcu);
    
    /* DMA init config */
    dma_struct_para_init(&uart_drv->dma.init);
    
    uart_drv->dma.dma_periph = uart_drv->config->dma_rx->dma_periph;
    uart_drv->dma.channel    = uart_drv->config->dma_rx->channel;
    
    uart_drv->dma.init.direction    = DMA_PERIPHERAL_TO_MEMORY;
    uart_drv->dma.init.periph_inc   = DMA_PERIPH_INCREASE_DISABLE;
    uart_drv->dma.init.memory_inc   = DMA_MEMORY_INCREASE_ENABLE;
    uart_drv->dma.init.periph_width = DMA_PERIPHERAL_WIDTH_8BIT;
    uart_drv->dma.init.memory_width = DMA_PERIPHERAL_WIDTH_8BIT;
    uart_drv->dma.init.priority     = DMA_PRIORITY_MEDIUM;
    
    uart_drv->dma.init.periph_addr  = uart_drv->config->periph + 0x04U; //USART_DATA regiest
    uart_drv->dma.init.memory_addr  = (uint32_t)rx_fifo->buffer;
    uart_drv->dma.init.number       = serial->config.bufsz;
    
    
    dma_deinit(uart_drv->dma.dma_periph,uart_drv->dma.channel);    

    dma_init(uart_drv->dma.dma_periph,uart_drv->dma.channel,&uart_drv->dma.init); 
    dma_circulation_enable(uart_drv->dma.dma_periph,uart_drv->dma.channel);
    dma_memory_to_memory_disable(uart_drv->dma.dma_periph,uart_drv->dma.channel);
    
    NVIC_EnableIRQ(uart_drv->config->irq_type);
    nvic_irq_enable(uart_drv->config->irq_type,1,0);
    
    nvic_irq_enable(uart_drv->config->dma_rx->dma_irq,0,0);
    NVIC_EnableIRQ(uart_drv->config->dma_rx->dma_irq);
    
    usart_interrupt_enable(uart_drv->config->periph,USART_INT_IDLE);
    dma_interrupt_enable(uart_drv->dma.dma_periph,uart_drv->dma.channel,DMA_INT_FTF);
    usart_dma_receive_config(uart_drv->config->periph,USART_DENR_ENABLE);
    
    dma_channel_enable(uart_drv->dma.dma_periph,uart_drv->dma.channel);
    LOG_D("%s dma RX instance: %x", uart_drv->config->name, uart->dma.handle.Instance);
    LOG_D("%s dma config done", uart_drv->config->name);
}
#endif  /* RT_SERIAL_USING_DMA */

static void stm32_uart_get_dma_config(void)
{
#ifdef BSP_UART0_RX_USING_DMA
    uart_obj[UART0_INDEX].uart_dma_flag = 1;
    static struct dma_config uart0_dma_rx = UART0_DMA_CONFIG;
    uart_config[UART0_INDEX].dma_rx = &uart0_dma_rx;
#endif    
#ifdef BSP_UART1_RX_USING_DMA
    uart_obj[UART1_INDEX].uart_dma_flag = 1;
    static struct dma_config uart1_dma_rx = UART1_DMA_CONFIG;
    uart_config[UART1_INDEX].dma_rx = &uart1_dma_rx;
#endif
#ifdef BSP_UART2_RX_USING_DMA
    uart_obj[UART2_INDEX].uart_dma_flag = 1;
    static struct dma_config uart2_dma_rx = UART2_DMA_CONFIG;
    uart_config[UART2_INDEX].dma_rx = &uart2_dma_rx;
#endif
#ifdef BSP_UART3_RX_USING_DMA
    uart_obj[UART3_INDEX].uart_dma_flag = 1;
    static struct dma_config uart3_dma_rx = UART3_DMA_CONFIG;
    uart_config[UART3_INDEX].dma_rx = &uart3_dma_rx;
#endif
#ifdef BSP_UART4_RX_USING_DMA
    uart_obj[UART4_INDEX].uart_dma_flag = 1;
    static struct dma_config uart4_dma_rx = UART4_DMA_CONFIG;
    uart_config[UART4_INDEX].dma_rx = &uart4_dma_rx;
#endif
}

int rt_hw_usart_init(void)
{
    rt_size_t obj_num = sizeof(uart_obj) / sizeof(struct uart_driver);
    struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
    rt_err_t result = 0;
    
    stm32_uart_get_dma_config();
    
    for (int i = 0; i < obj_num; i++)
    {
        uart_obj[i].config = &uart_config[i];
        uart_obj[i].serial.ops    = &uart_ops;
        uart_obj[i].serial.config = config;
        
#if defined(RT_SERIAL_USING_DMA)     
        if(uart_obj[i].uart_dma_flag)
        {
            /* register UART device */
//            result = rt_hw_serial_register(&uart_obj[i].serial,uart_obj[i].config->name,
//                                           RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX| RT_DEVICE_FLAG_DMA_RX 
//                                           ,&uart_obj[i]);
            
            result = rt_hw_serial_register(&uart_obj[i].serial,uart_obj[i].config->name,
                                           RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_DMA_RX  | RT_DEVICE_FLAG_INT_RX
                                           ,&uart_obj[i]);            
        }
        else
#endif       
        {
            /* register UART device */
            result = rt_hw_serial_register(&uart_obj[i].serial,uart_obj[i].config->name,
                                           RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX
                                           ,&uart_obj[i]);
        }
        RT_ASSERT(result == RT_EOK);
    }

    return result;
}
INIT_BOARD_EXPORT(rt_hw_usart_init);

#endif /* RT_USING_SERIAL */
